package com.study.springboot.factory;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author huyong
 * @Decription
 * @date 2025-03-27 15:12
 */
@Component
public class AuthRoutePredicateFactory extends AbstractRoutePredicateFactory<AuthRoutePredicateFactory.Config> {
    public static final String APP_NAME = "appName";
    public static final String APP_SECRET = "appSecret";

    public AuthRoutePredicateFactory() {
        super(Config.class);
    }

    /**
     * 指定配置项读取的顺序
     *
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("appName", "appSecret");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exechange -> {
            //获取请求中所有的header
            HttpHeaders headers = exechange.getRequest().getHeaders();
            List<String> appNameList = headers.get(APP_NAME);
            List<String> appSecretList = headers.get(APP_SECRET);
            if (CollectionUtils.isEmpty(appSecretList) || CollectionUtils.isEmpty(appNameList)) {
                return false;
            }
            return appSecretList.contains(config.getAppSecret()) && appNameList.contains(config.getAppName());
        };
    }

    /**
     * 从配置文件中读取的配置要封装在这里
     */
    public static class Config {

        /**
         * 应用名称
         */
        private String appName;
        /**
         * 应用唯一标识
         */
        private String appSecret;

        public String getAppName() {
            return appName;
        }

        public void setAppName(String appName) {
            this.appName = appName;
        }

        public String getAppSecret() {
            return appSecret;
        }

        public void setAppSecret(String appSecret) {
            this.appSecret = appSecret;
        }
    }
}
